package com.movie.service.impl;

import com.movie.entity.Seat;
import com.movie.mapper.SeatMapper;
import com.movie.service.SeatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SeatServiceImpl implements SeatService {

    @Autowired
    private SeatMapper seatMapper;

    @Override
    public List<Seat> getSeatsByShowtimeId(Long showtimeId) {
        return seatMapper.findByShowtimeId(showtimeId);
    }

    @Override
    @Transactional
    public boolean initializeSeats(Long showtimeId, int rows, int columns) {
        // 固定为10行10列，确保每个场次都有100个座位
        rows = 10;
        columns = 10;

        // 创建座位列表
        List<Seat> seats = new ArrayList<>();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                Seat seat = new Seat();
                seat.setShowtimeId(showtimeId);
                seat.setRowIndex(i);
                seat.setColumnIndex(j);
                seat.setStatus(Seat.STATUS_AVAILABLE); // 初始状态为可用
                seats.add(seat);
            }
        }

        // 批量插入座位
        try {
            int insertedRows = seatMapper.batchInsert(seats);
            return insertedRows == seats.size();
        } catch (Exception e) {
            // 记录日志
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateSeatStatus(Long id, String status) {
        int updatedRows = seatMapper.updateStatus(id, status);
        return updatedRows > 0;
    }

    @Override
    public Seat getSeatByPosition(Long showtimeId, Integer rowIndex, Integer columnIndex) {
        return seatMapper.findByPosition(showtimeId, rowIndex, columnIndex);
    }

    @Override
    public Seat getSeatById(Long id) {
        return seatMapper.findById(id);
    }
}
